#!/usr/bin/env jq
# compile-config-9.99-dependencies -- Derives a dependency graph for easier Makefile and .dot codegen
##
.deepdive_ as $deepdive

# a handy map to find outputs_ by process name
| ( $deepdive.execution.processes | with_entries
    (.value |= (.output_ | if type == "null"  then null
                         elif type == "array" then .
                         else [.] end))
  ) as $output_relation
# form a dependency graph
| .deepdive_.execution.dependencies =
( [ # every process/* and the processes or input data it depends on
    ( $deepdive.execution.processes | to_entries[]
    | .value |= (([.dependencies_[]? | ($output_relation[.] // [.])[]]) + .input_ | unique)
    )
  , # every output_ depends on the process that output it
    ( $output_relation | to_entries
    # repeat map entries for every output_
    | [ map({ key: .key, value: .value[]? })[] ]
    # invert the mappings
    | group_by(.value)[]
    | { key: (.[0].value // empty), value: map(.key) }
    )
  ]
| from_entries
)
